package cn.iocoder.yudao.module.signature.validatap12status.cermb;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 描述文件解析工具类
 */
public class ProvisioningProfileUtils {
    
    private static final Logger logger = LoggerFactory.getLogger(ProvisioningProfileUtils.class);
    
    /**
     * 解析描述文件
     */
    public static ProvisioningProfileInfo parseProvisioningProfile(String profilePath) {
        try {
            // 描述文件是plist格式，需要解析
            String profileContent = readFileContent(profilePath);
            if (profileContent == null) {
                return null;
            }
            
            ProvisioningProfileInfo profileInfo = new ProvisioningProfileInfo();
            
            // 解析UUID
            String uuid = extractPlistValue(profileContent, "UUID");
            profileInfo.setUuid(uuid);
            
            // 解析名称
            String name = extractPlistValue(profileContent, "Name");
            profileInfo.setName(name);
            
            // 解析AppIDName
            String appIdName = extractPlistValue(profileContent, "AppIDName");
            profileInfo.setAppIdName(appIdName);
            
            // 解析TeamIdentifier
            String teamId = extractPlistValue(profileContent, "TeamIdentifier");
            profileInfo.setTeamIdentifier(teamId);
            
            // 解析证书指纹列表
            String[] fingerprints = extractCertificateFingerprints(profileContent);
            profileInfo.setCertificateFingerprints(fingerprints);
            
            // 解析设备UDID列表
            String[] deviceIds = extractDeviceIds(profileContent);
            profileInfo.setDeviceIds(deviceIds);
            
            // 解析Entitlements
            Map<String, Object> entitlements = extractEntitlements(profileContent);
            profileInfo.setEntitlements(entitlements);
            
            logger.info("解析描述文件成功: {}", profileInfo);
            return profileInfo;
            
        } catch (Exception e) {
            logger.error("解析描述文件失败", e);
            return null;
        }
    }
    
    /**
     * 读取文件内容
     */
    private static String readFileContent(String filePath) {
        try {
            StringBuilder content = new StringBuilder();
            try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) {
                String line;
                while ((line = reader.readLine()) != null) {
                    content.append(line).append("\n");
                }
            }
            return content.toString();
        } catch (IOException e) {
            logger.error("读取文件失败: {}", filePath, e);
            return null;
        }
    }
    
    /**
     * 从plist中提取值
     */
    private static String extractPlistValue(String content, String key) {
        Pattern pattern = Pattern.compile("<key>" + key + "</key>\\s*<string>(.*?)</string>");
        Matcher matcher = pattern.matcher(content);
        if (matcher.find()) {
            return matcher.group(1);
        }
        return null;
    }
    
    /**
     * 提取证书指纹列表
     */
    private static String[] extractCertificateFingerprints(String content) {
        // 查找DeveloperCertificates数组
        Pattern pattern = Pattern.compile("<key>DeveloperCertificates</key>\\s*<array>(.*?)</array>", Pattern.DOTALL);
        Matcher matcher = pattern.matcher(content);
        if (matcher.find()) {
            String certsSection = matcher.group(1);
            // 这里需要解析base64编码的证书数据并计算指纹
            // 简化实现，实际应该解析证书数据
            return new String[0];
        }
        return new String[0];
    }
    
    /**
     * 提取设备ID列表
     */
    private static String[] extractDeviceIds(String content) {
        Pattern pattern = Pattern.compile("<key>ProvisionedDevices</key>\\s*<array>(.*?)</array>", Pattern.DOTALL);
        Matcher matcher = pattern.matcher(content);
        if (matcher.find()) {
            String devicesSection = matcher.group(1);
            // 解析设备ID列表
            Pattern devicePattern = Pattern.compile("<string>(.*?)</string>");
            Matcher deviceMatcher = devicePattern.matcher(devicesSection);
            List<String> devices = new ArrayList<>();
            while (deviceMatcher.find()) {
                devices.add(deviceMatcher.group(1));
            }
            return devices.toArray(new String[0]);
        }
        return new String[0];
    }
    
    /**
     * 提取Entitlements
     */
    private static Map<String, Object> extractEntitlements(String content) {
        Map<String, Object> entitlements = new HashMap<>();
        // 简化实现，实际应该解析Entitlements字典
        return entitlements;
    }
    
    /**
     * 检查证书指纹是否在描述文件中
     */
    public static boolean isCertificateFingerprintInProfile(String certificateFingerprint, 
                                                           ProvisioningProfileInfo profileInfo) {
        if (profileInfo.getCertificateFingerprints() == null) {
            return false;
        }
        
        for (String profileFingerprint : profileInfo.getCertificateFingerprints()) {
            if (certificateFingerprint.equalsIgnoreCase(profileFingerprint)) {
                return true;
            }
        }
        return false;
    }
    
    /**
     * 检查Team ID是否匹配
     */
    public static boolean isTeamIdMatch(String certificateTeamId, ProvisioningProfileInfo profileInfo) {
        if (certificateTeamId == null || profileInfo.getTeamIdentifier() == null) {
            return false;
        }
        return certificateTeamId.equals(profileInfo.getTeamIdentifier());
    }
} 